package xyz.bali16.application.security.exception;


import com.google.gson.Gson;
import lombok.AllArgsConstructor;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import xyz.bali16.application.core.enums.ApiEnum;
import xyz.bali16.application.core.enums.HttpStatusEnum;
import xyz.bali16.application.core.model.Result;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@AllArgsConstructor
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    private final Gson gson;

    @Override
    public void handle(HttpServletRequest httpServletRequest,
                       HttpServletResponse httpServletResponse,
                       AccessDeniedException e) throws IOException {
        httpServletResponse.setStatus(HttpStatusEnum.FORBIDDEN.getCode());
        httpServletResponse.setHeader("Content-Type", "application/json;charset=UTF-8");
        httpServletResponse.getWriter().write(
                gson.toJson(Result.response(ApiEnum.OPERATE_ERROR, e.getMessage()))
        );
    }
}
